import React from 'react';
import ReactDom from 'react-dom';
import './style';


var classNames = require("classnames");

class Modal extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            show: this.props['show'],
            drawerToOpen: false
        }
        this.el = document.createElement('div');
    }

    componentDidMount() {
        const modalRoot = this.props['modalRoot'] || document.body;
        modalRoot.style.position = "relative";
        console.log(modalRoot, "========modalRoot========");
        modalRoot.appendChild(this.el);

        setTimeout(() => {
            this.setState({
                drawerToOpen: true
            })
        }, 0);
    }

    componentWillUnmount() {
        const modalRoot = this.props['modalRoot'] || document.body;
        modalRoot.style.position = "";
        modalRoot.removeChild(this.el);
    }

    // 在componentDidUpdate中进行异步操作，驱动数据的变化
    componentDidUpdate(prevProps, prevState) {
        if (this.props['show'] !== prevProps['show']) {
            this.setState({
                show: this.props['show']
            })
        }
    }


    onInnerCancel = () => {
        this.setState({
            drawerToOpen: false
        })
        setTimeout(() => {
            this.props.onCancel();
        }, 300);
    }


    render() {

        var { okButtonProps, className, wrapStyle, bodyStyle, show, width, height, size, onCancel, onOk, okText = "确定", cancelText = "取消", title, ...rest } = this.props;

        var cls = classNames("kd-drawer", className, { 'kd-drawer-open': this.state.drawerToOpen })

        return this.state.show ? ReactDom.createPortal(
            <>
                <div className="kd-mask maskFadeIn" onClick={this.onInnerCancel}></div>
                <div className={cls} style={{ height: height, width: width }} {...rest}>
                    <div className="kd-drawer-header">

                        <div className="left">
                            {title}
                        </div>

                        <div className="right">
                            <div className="right_close_icon" onClick={this.onInnerCancel} ></div>
                        </div>
                    </div>
                    <div className="kd-drawer-body" style={{ ...bodyStyle }} >
                        {this.props.children}
                    </div>
                    <div className="kd-drawer-footer">

                    </div>

                </div>
            </>,
            this.el
        ) : null

    }
}

export default Modal;